package com.android.interfata;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.menu.MenuAbout;
import com.android.menu.MenuContact;
import com.android.menu.MenuHelp;
import com.android.menu.MenuLegal;

public class Login  extends Activity
{

	private int numResults;
	private String succes;
	private String mesaj;
	private int ID;
    private String username;
    private String parola;
    private String nume;
    private String prenume;
    private String email;
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        /*
         * ascunde username si logout din header
         */
        TextView user = (TextView) findViewById(R.id.userHeader);
        TextView logout = (TextView) findViewById(R.id.logoutHeader);
        user.setVisibility(View.INVISIBLE);
        logout.setVisibility(View.INVISIBLE);
        
        
        // menu
        
        
        
        // Listening to register new account link
        TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
        registerScreen.setOnClickListener(new View.OnClickListener()
        {	
			public void onClick(View v)
			{
				// Switching to Register screen
 				//Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://cotrobaie.cjb.net//login.aspx"));
				Intent i = new Intent (getApplicationContext(), Register.class);
				startActivity(i);
			}
		});

        
        Button login = (Button) findViewById(R.id.btnLogin);
        login.setOnClickListener(new View.OnClickListener()
        {
			
			public void onClick(View v) 
			{
				loginData();
			}
		});
    }
    
    
    /* trimit username-ul si parola la server ca sa le verific */
    private void loginData()
    {
    	AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
    	EditText ed_user = (EditText) findViewById(R.id.log_username);
    	EditText ed_pass = (EditText) findViewById(R.id.log_password);
    	String user = ed_user.getText().toString();
    	String pass = ed_pass.getText().toString();
    	
    	if (user.equals("") || pass.equals(""))		// campurile trebuie sa fie completate 
    	{
	        dlgAlert.setMessage("'Username' or 'Password' field left blank");
	        dlgAlert.setTitle("Warning");
	        dlgAlert.setPositiveButton("OK", null);
	        dlgAlert.setCancelable(true);
	        dlgAlert.create().show();
    	}
    	else 
    	{
	    	try 
	    	{
	    		user = replace(user, " ", "%20");
	    		pass = replace(pass, " ", "%20");
	    		String xml = XMLfunctions.getXML("Login?UserUsername=" + user + "&Password=" + pass);
	    		Log.d("xml", xml);
	    		Document doc = XMLfunctions.XMLfromString(xml);	    		
		        numResults = XMLfunctions.numResults(doc, "Username");
		        Log.d("num", numResults + " ");
		        if (numResults != 1) 		// trebuie sa fie un singur raspuns (nu pot fi doi utilizatori cu aceleasi date)
		        {
		        	NodeList nodes = doc.getElementsByTagName("Mesaj");
			        Element e = (Element)nodes.item(0);
			        succes = XMLfunctions.getValue(e, "Success");
			        mesaj = XMLfunctions.getValue(e, "Mesaj");
			        
			        dlgAlert.setMessage(mesaj);
			        dlgAlert.setTitle("Error");
			        dlgAlert.setPositiveButton("OK", null);
			        dlgAlert.setCancelable(true);
			        dlgAlert.create().show();		        	
		        }
		        else
		        {
			        NodeList nodes = doc.getElementsByTagName("User");
			        Element e = (Element)nodes.item(0);
			        
			        succes = XMLfunctions.getValue(e, "Success");
			        mesaj = XMLfunctions.getValue(e, "Mesaj");
			        if (succes.equals("false"))
			        {
				        dlgAlert.setMessage(mesaj + "ceva");
				        dlgAlert.setTitle("Error");
				        dlgAlert.setPositiveButton("OK", null);
				        dlgAlert.setCancelable(true);
				        dlgAlert.create().show();	
			        }
			        else 
			        {
				        ID = Integer.parseInt(XMLfunctions.getValue(e, "ID"));
				        username = XMLfunctions.getValue(e, "Username");
				        parola = XMLfunctions.getValue(e, "Parola");
				        nume = XMLfunctions.getValue(e, "Nume");
				        prenume = XMLfunctions.getValue(e, "Prenume");
				        email = XMLfunctions.getValue(e, "Email");
				        
				        addToPref(ID, username, parola, nume, prenume, email);
				        
				        Intent intent = new Intent(getApplicationContext(), InterfActivity.class);
						intent.putExtra("activity", 0);
						startActivity(intent);
			        }       
		        }
	    	}
	    	catch (Exception exc)
	    	{
	    		Log.e("CErr", "eroare in loginData " + exc.getLocalizedMessage());
	    	}
    	}
    }
    
    // inlocuiesc spatiile
	static String replace(String str, String pattern, String replace)
	{
		String str1;
		int i = 0;
		while (i < str.length())
		{
			
			if ( str.charAt(i) == ' '  && str.charAt(i+1) == ' ')
			{
				str1 = str.substring(0, i) + str.substring(i + 2, str.length());
				str = str1;
			}
			else
				i++;
		}	
		
	    int s = 0;
	    int e = 0;
	    StringBuffer result = new StringBuffer();

	    while ((e = str.indexOf(pattern, s)) >= 0)
	    {
	        result.append(str.substring(s, e));
	        result.append(replace);
	        s = e+pattern.length();
	    }
	    result.append(str.substring(s));
	    return result.toString();
	}
    
    private void addToPref(int ID, String user, String pass, String nume, String prenume, String email)
    {
    	SharedPreferences logPref = getSharedPreferences("LoginPref", MODE_PRIVATE);  
    	SharedPreferences.Editor prefEditor = logPref.edit();  
    	prefEditor.putInt("ID", ID);  
    	prefEditor.putString("user", user);  
    	prefEditor.putString("pass", pass);  
    	prefEditor.putString("nume", nume);  
    	prefEditor.putString("prenume", prenume);  
    	prefEditor.putString("email", email);  
    	
    	CheckBox remember = (CheckBox) findViewById(R.id.remember);
    	if (remember.isChecked() == true)
    	{
    		prefEditor.putBoolean("remember", true);
    	}
    	else
    	{
    		prefEditor.putBoolean("remember", false);    		
    	}
    	prefEditor.commit(); 
    }
    
    public void onCheckboxClicked(View v) 
    {
        // Perform action on clicks, depending on whether it's now checked
        if (((CheckBox) v).isChecked()) {
            Toast.makeText(getApplicationContext(), "Selected", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Not selected", Toast.LENGTH_SHORT).show();
        }
    }
    
    
	/*     menu      */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	Intent intent;
        switch (item.getItemId()) 
        {
            case R.id.menu_about:     
            	intent = new Intent(getApplicationContext(), MenuAbout.class);
				startActivity(intent);
                break;
            case R.id.menu_help:     
            	intent = new Intent(getApplicationContext(), MenuHelp.class);
				startActivity(intent);
                break;
            case R.id.menu_legal: 
            	intent = new Intent(getApplicationContext(), MenuLegal.class);
				startActivity(intent);
            	break;
            case R.id.menu_contact:
            	intent = new Intent(getApplicationContext(), MenuContact.class);
				startActivity(intent);
            	break;
        }
        return true;
    }
	/*     end menu      */
}
